package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.sky.constant.OrdersConstant.*;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 0/1 * * * ? ") // 每分钟执行一次
    public void processTimeoutOrder(){
        log.info("定时清理超时订单：{}", LocalDateTime.now());

        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        // 查询超时并且未支付的订单
        List<Orders> orders =  orderMapper.getByStatusAndOrderTime(ORDERS_STATUS_OBLIGATION, orderTime);

        for (Orders order : orders) {
            order.setStatus(ORDERS_STATUS_CANCELED);
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason(CANCEL_REASON);
            orderMapper.update(order);
        }
    }


    /**
     * 处理已送达订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理已送达订单{}", LocalDateTime.now());

        LocalDateTime orderTime = LocalDateTime.now().minusHours(1);

        // 查询派送中的订单
        List<Orders> orders =  orderMapper.getByStatusAndOrderTime(ORDERS_STATUS_DELIVERY, orderTime);

        for (Orders order : orders) {
            order.setStatus(Orders.COMPLETED);
            orderMapper.update(order);
        }
    }
}
